// API配置
const API_CONFIG = {
  baseURL: 'http://192.168.8.46:8080',
  token: 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxODgzMDE5MzEzMCIsImxvZ2luX3VzZXJfa2V5IjoiMTUyY2IzYTMtOWFhZC00ZTYxLWExZTAtY2UwZjFlMzUxMTc4In0.UJ8Q8JTEaMd7-z7kp1oguBwWDVXtzAfCCqxW_PsUidT2OmCIsTqPfu8TAf6S8zAVfFKFiZTCnE1D9V_Eaqp1hw'
};

// 通用请求函数
async function apiRequest(endpoint, options = {}) {
  const url = `${API_CONFIG.baseURL}${endpoint}`;

  // 默认头部配置
  const defaultHeaders = {
    'authorization': API_CONFIG.token
  };

  // 只有当body不是FormData时，才设置Content-Type为application/json
  if (!(options.body instanceof FormData)) {
    defaultHeaders['Content-Type'] = 'application/json';
  }

  const defaultOptions = {
    headers: defaultHeaders,
    ...options.headers
  };

  try {
    const response = await fetch(url, { ...defaultOptions, ...options });

    if (!response.ok) {
      throw new Error(`API请求失败: HTTP ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error('API请求错误:', error);
    throw error;
  }
}

// VR数据相关API
export const vrAPI = {
  // 获取VR数据列表
  getVRList: async (pageNum, pageSize, lineId = 430) => {
    const data = await apiRequest(`/line/line_point_vr/lineVrs?pageNum=${pageNum}&pageSize=${pageSize}&lineId=${lineId}`);

    // 调试输出，查看实际返回的数据结构
    console.log('API返回数据:', data);

    // 根据返回数据结构调整
    return data;
  }
};

// 留言相关API
export const commentAPI = {
  // 获取留言列表
  getComments: (pointVrId, pageNum, pageSize) => {
    return apiRequest(`/line/vr_message/getList?pageNum=${pageNum}&pageSize=${pageSize}&pointVrId=${pointVrId}`);
  },

  // 提交留言
  submitComment: (pointVrId, messageContent) => {
    return apiRequest('/line/vr_message/save', {
      method: 'POST',
      body: JSON.stringify({ pointVrId, messageContent })
    });
  }
};

// 达人足迹相关API
export const influencerAPI = {
  // 上传达人足迹
  uploadInfluencerTrail: (pointVrId, mediaUrl, mediaType, description) => {
    return apiRequest('/line/vr_talent/save', {
      method: 'POST',
      body: JSON.stringify({ pointVrId, mediaUrl, mediaType, description })
    });
  },
  
  // 获取达人足迹列表
  getInfluencerTrails: async (pointVrId, pageNum = 1, pageSize = 10) => {
    try {
      // 调用真实的API接口
      const data = await apiRequest(`/line/vr_talent/getList?pageNum=${pageNum}&pageSize=${pageSize}&pointVrId=${pointVrId}`);

      console.log(`获取达人足迹列表成功：pointVrId=${pointVrId}, 第${pageNum}页`, data);

      // 根据后端返回的数据结构进行调整
      if (data.code === 200) {
        return {
          code: 200,
          msg: 'success',
          total: data.total || 0,
          rows: data.rows || data.data || []
        };
      } else {
        throw new Error(data.msg || '获取达人足迹失败');
      }
    } catch (error) {
      console.error('获取达人足迹失败:', error);
      throw error;
    }
  }
};

//上传图片/视频
export const fileAPI = {
  // 上传图片/视频
  uploadMedia: (file) => {
    // 创建FormData对象
    const formData = new FormData();
    formData.append('file', file);

    return apiRequest('/system/oss/upload', {
      method: 'POST',
      body: formData
    });
  },
  // 删除图片/视频
  deleteMedia: (url) => {
    return apiRequest('/system/oss/delete', {
      method: 'POST',
      body: JSON.stringify({ url })
    });
  }
};

// 用户相关API
export const userAPI = {
  // 获取用户信息
  getUserInfo: () => {
    return apiRequest('/line/user/info', {
      method: 'GET'
    });
  },

  // 关注/取消关注用户
  followOrUnfollow: (userId, status) => {
    return apiRequest('/line/user/concernOrCancel', {
      method: 'POST',
      body: JSON.stringify({ userId, status })
    });
  }
};